package com.icinfo.cloud.provider.punish.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.provider.common.dto.FileInfoSaveDto;
import com.icinfo.cloud.provider.common.enums.ApiVisitDataSourceEnum;
import com.icinfo.cloud.provider.common.enums.AttachmentRequestContentTypeEnum;
import com.icinfo.cloud.provider.common.enums.FileTransferFormEnum;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.oss.service.IOssOperateService;
import com.icinfo.cloud.provider.common.utils.Base64ToMultipartFileUtil;
import com.icinfo.cloud.provider.peripheralinterface.xfjdzf.service.impl.XfjdzfInterfaceServiceImpl;
import com.icinfo.cloud.provider.punish.api.dto.ApiSimpleCaseDetailInfoCallbackDto;
import com.icinfo.cloud.provider.punish.api.dto.ApiSimpleCaseDetailInfoDto;
import com.icinfo.cloud.provider.punish.api.dto.ApiSimpleCaseTemporaryCacheDto;
import com.icinfo.cloud.provider.punish.api.service.IApiSimpleCaseService;
import com.icinfo.cloud.provider.punish.api.vo.ApiSimpleCaseDetailInfoVo;
import com.icinfo.cloud.provider.punish.dto.CaseEvidencePhotoDto;
import com.icinfo.cloud.provider.punish.dto.CaseReasonQueryDto;
import com.icinfo.cloud.provider.punish.dto.SimpleCaseSaveDto;
import com.icinfo.cloud.provider.punish.mapper.CaseTemporaryRecordMapper;
import com.icinfo.cloud.provider.punish.service.ICaseMainInfoService;
import com.icinfo.cloud.provider.punish.service.ISimpleCaseService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseDetailInfoQueryDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.HandlePersonTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartyTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseDetailSimpleInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseHandlePersonRecordVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesInfoVo;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.CaseHandlePersonInfoDto;
import com.icinfo.cloud.provider.punish.vo.CaseMainQueryByYearVo;
import com.icinfo.cloud.provider.punish.vo.CaseMainRepeatVo;
import com.icinfo.framework.common.web.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述：简易处罚应用服务接口实现类
 *
 * @author xiangyuyu
 * @date 2022/8/11
 * @since 1.3.2
 */
@Service
@Slf4j
public class ApiSimpleCaseServiceImpl implements IApiSimpleCaseService {
    @Resource
    private ISimpleCaseService simpleCaseService;
    @Resource
    private IOssOperateService iOssOperateService;
    @Resource
    private CaseTemporaryRecordMapper caseTemporaryRecordMapper;
    @Resource
    private ICaseMainInfoService caseMainInfoService;

    /**
     * 【V1.3.2】描述：api-简易处罚信息缓存
     *
     * @param dto {@link ApiSimpleCaseTemporaryCacheDto}
     * @return Result<String> 缓存结果
     * @author xiangyuyu
     * @date 2022/8/11
     * @since 1.3.2
     */
    @Override
    public Result<String> simpleCaseTemporaryCache(ApiSimpleCaseTemporaryCacheDto dto) {
        log.info("ApiSimpleCaseServiceImpl.simpleCaseTemporaryCache start... dto:{}", dto);
        String errorMsg = validatedSimpleCaseTemporaryCacheInfo(dto);
        if (!ObjectUtils.isEmpty(errorMsg)) {
            return Result.error(errorMsg);
        }
        SimpleCaseSaveDto saveDto = new SimpleCaseSaveDto();
        BeanUtils.copyProperties(dto, saveDto);
        String dataSource = dto.getDataSource();
        if(!ObjectUtils.isEmpty(dataSource)){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("dataSource",dataSource);
            saveDto.setExtraJsonInfo(jsonObject.toJSONString());
        }
        saveDto.setIsAutoSave(YesOrNoEnum.NO.getCode());
        saveDto.setAddressLatLongitude(dto.getCaseHappenAddressLocationInfo());
        //处理取证照片base64信息，上传统一处罚oss
        List<CaseEvidencePhotoDto> caseEvidencePhotoList = dto.getCaseEvidencePhotoList();
        if(!ObjectUtils.isEmpty(caseEvidencePhotoList)) {
            analyseAttachmentToOss(caseEvidencePhotoList);
        }
        saveDto.setCaseEvidencePhotoList(caseEvidencePhotoList);
        saveDto.setIsFirstCache(YesOrNoEnum.YES.getCode());
        int count = simpleCaseService.saveTemporary(saveDto);
        if (count > 0) {
            log.info("ApiSimpleCaseServiceImpl.simpleCaseTemporaryCache end response:{}", "暂存成功");
            return Result.success("接收成功");
        }
        log.info("ApiSimpleCaseServiceImpl.simpleCaseTemporaryCache end response:{}", "暂存失败");
        return Result.error("保存失败");
    }
    /**
     * 描述：解析附件信息并上传至oss
     *
     * @param caseEvidencePhotoList 附件信息
     * @author xiangyuyu
     * @date 2022/8/13
     * @since 1.3.2
     */
    private void analyseAttachmentToOss(List<CaseEvidencePhotoDto> caseEvidencePhotoList) {
        log.info("analyseAttachmentToOss start...caseEvidencePhotoList:{}", caseEvidencePhotoList);
        for (CaseEvidencePhotoDto e : caseEvidencePhotoList) {
            String base64Info = e.getFileBase64Info();
            try {
                if (!ObjectUtils.isEmpty(base64Info)) {
                    /*if(!base64Info.startsWith("data:image")){
                        base64Info = "data:image/png;base64,"+base64Info;
                    }*/
                    //base64转字节数组
                    base64Info =  base64Info.replace("\r","");
                    base64Info =  base64Info.replace("\n","");
                    Base64ToMultipartFileUtil util = new Base64ToMultipartFileUtil(base64Info);
                    byte[] fileBytes = util.getBytes();
                    //上传oss
                    FileInfoSaveDto fileInfo = new FileInfoSaveDto();
                    fileInfo.setFileBytes(fileBytes);
                    fileInfo.setFileTransferForm(FileTransferFormEnum.FILE_TRANSFER_FORM_3.getCode());
                    fileInfo.setFileType(AttachmentRequestContentTypeEnum.jpg.getCode());
                    Result result = iOssOperateService.uploadFile(fileInfo);
                    if (!ObjectUtils.isEmpty(result)) {
                        String ossUrl = result.getData().toString();
                        e.setFileUrl(ossUrl);
                        e.setFileName(util.getOriginalFilename());
                        e.setFileBase64Info(null);
                    }
                }
            } catch (Exception exe) {
                exe.printStackTrace();
                throw new BusinessException("解析简易处罚附件信息时出现异常");
            }
        }
    }


    /**
     * 描述：简易处罚案件信息暂存信息校验
     *
     * @param dto {@link ApiSimpleCaseTemporaryCacheDto}
     * @return String 错误信息
     * @author xiangyuyu
     * @date 2022/8/11
     * @since 1.3.2
     */
    private String validatedSimpleCaseTemporaryCacheInfo(ApiSimpleCaseTemporaryCacheDto dto) {
        String dataSource = dto.getDataSource();
        if (!ApiVisitDataSourceEnum.isLegalEnumId(dataSource)) {
            return "未指定已授权的数据来源";
        }
        List<CaseHandlePersonInfoDto> handlePersonInfoList = dto.getHandlePersonInfoList();
        if (ObjectUtils.isEmpty(handlePersonInfoList) || handlePersonInfoList.size() == 0) {
            return "未指定办案人员信息列表信息";
        }
        boolean isExistsMainHandler = false;
        for (CaseHandlePersonInfoDto e : handlePersonInfoList) {
            String handlePersonType = e.getHandlePersonType();
            if (HandlePersonTypeEnum.MAIN.getCode().equals(handlePersonType)) {
                isExistsMainHandler = true;
                String orgCode = e.getHandleOrgCode();
                if (ObjectUtils.isEmpty(orgCode)) {
                    return "未指定主办人员对应机构编码";
                }
            }
        }
        if (!isExistsMainHandler) {
            return "未指定主办人员信息";
        }
        return "";
    }

    /**
     * 【V1.3.2】描述：获取简易处罚案件详情
     *
     * @param dto {@link ApiSimpleCaseDetailInfoDto}
     * @return Result<ApiSimpleCaseDetailInfoVo> 简易处罚案件详情
     * @author xiangyuyu
     * @date 2022/8/11
     * @since 1.3.2
     */
    @Override
    public ApiSimpleCaseDetailInfoVo getSimpleCaseDetailInfo(ApiSimpleCaseDetailInfoDto dto) {
        ApiSimpleCaseDetailInfoVo vo = null;
        String caseId = dto.getCaseId();
        CaseDetailInfoQueryDto queryDto = new CaseDetailInfoQueryDto();
        queryDto.setCaseId(caseId);
        CaseDetailSimpleInfoVo caseDetailSimpleInfo = caseMainInfoService.getSimpleCaseDetailInfo(queryDto);
        if (!ObjectUtils.isEmpty(caseDetailSimpleInfo)) {
                //数据处理
                vo = new ApiSimpleCaseDetailInfoVo();
                BeanUtils.copyProperties(caseDetailSimpleInfo, vo);
                //当事人信息
                CasePartiesInfoVo p = caseDetailSimpleInfo.getCasePartiesInfoVo();
                if(!ObjectUtils.isEmpty(p)){
                    String partyType = p.getPartyType();
                    vo.setPartyType(partyType);
                    if(PartyTypeEnum.PERSON.getCode().equals(partyType)){
                        vo.setName(p.getPartyName());
                        vo.setSex(p.getSex());
                        vo.setBirth(p.getBirth());
                        vo.setAge(p.getAge());
                        vo.setMobile(p.getContactPhone());
                        vo.setCertType(p.getPartyIdentityType());
                        vo.setCertNo(p.getPartyIdentityCode());
                        vo.setAddress(p.getAddress());
                        vo.setUnitName(p.getWorkUnitName());
                        vo.setNationality(p.getNationality());
                    } else {
                        vo.setLegal(p.getPartyName());
                        vo.setJob(p.getJob());
                        vo.setUniscid(p.getPartyIdentityCode());
                        vo.setPhone(p.getContactPhone());
                        vo.setLegalCertNo(p.getLegalCertNo());
                        vo.setLegalCertType(p.getLegalCertType());
                        vo.setEntName(p.getPartyName());
                        vo.setEntType(p.getEntType());
                        vo.setBusinessAddress(p.getBusinessAddress());
                    }
                    vo.setPartyId(p.getPartyId());

                    //获取违法列表相关信息
                    CaseReasonQueryDto q = new CaseReasonQueryDto();
                    q.setCaseReasonCode(caseDetailSimpleInfo.getCaseReasonCode());
                    q.setPartyIdentityCode((PartyTypeEnum.PERSON.getCode().equals(partyType))?vo.getCertNo():vo.getUniscid());
                    CaseMainQueryByYearVo caseMainQueryByYearVo = simpleCaseService.getCaseMainListByReasonCodeAndParty(q);
                    if(!ObjectUtils.isEmpty(caseMainQueryByYearVo)){
                        List<CaseMainRepeatVo> partyReasonCaseList = caseMainQueryByYearVo.getPartyReasonCaseList();
                        List<CaseMainRepeatVo> partyCaseList = caseMainQueryByYearVo.getPartyCaseList();
                        vo.setIllegalNum(ObjectUtils.isEmpty(partyCaseList)?0:partyCaseList.size());
                        vo.setIllegalRepeatNum(ObjectUtils.isEmpty(partyReasonCaseList)?0:partyReasonCaseList.size());
                        vo.setIllegalInfoList(!ObjectUtils.isEmpty(partyCaseList)?partyCaseList:new ArrayList<>());
                        vo.setIllegalRepeatInfoList(!ObjectUtils.isEmpty(partyReasonCaseList)?partyReasonCaseList:new ArrayList<>());
                    }
                }
                List<CaseHandlePersonInfoDto> handlePersonInfoList = new ArrayList<>();
                List<CaseHandlePersonRecordVo> list = caseDetailSimpleInfo.getCaseHandlePersonList();
                list.forEach(e->{
                    CaseHandlePersonInfoDto caseHandlePersonInfo = new CaseHandlePersonInfoDto();
                    BeanUtils.copyProperties(e,caseHandlePersonInfo);
                    handlePersonInfoList.add(caseHandlePersonInfo);
                });
                vo.setHandlePersonInfoList(handlePersonInfoList);
        }

        return vo;
    }
}
